package top.lyc829.mymusic.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.lzx.starrysky.SongInfo
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.control.RepeatMode
import com.lzx.starrysky.manager.PlaybackStage
import top.lyc829.mymusic.ext.convertToSongInfo
import top.lyc829.mymusic.model.bean.Song

/**
 * @Author lyc
 * @create 2021-07-04 16:14
 */
class EventViewModel : ViewModel() {

    // 播放列表
    private val _playList: MutableLiveData<List<SongInfo>> by lazy { MutableLiveData() }
    val playList: LiveData<List<SongInfo>> get() = _playList

    private val _playBackState: MutableLiveData<PlaybackStage> by lazy { MutableLiveData() }
    val playBackStage: LiveData<PlaybackStage> get() = _playBackState

    private val _repeatMode: MutableLiveData<RepeatMode> by lazy { MutableLiveData(StarrySky.with().getRepeatMode()) }
    val repeatMode: LiveData<RepeatMode> get() = _repeatMode

    private fun setRepeatMode(repeatMode: Int, isLoop: Boolean = true) {
        _repeatMode.value = RepeatMode(repeatMode, isLoop)
        StarrySky.with().setRepeatMode(repeatMode, isLoop)
    }

    fun updateRepeatMode() {
        _repeatMode.value?.let {
            when (it.repeatMode) {
                RepeatMode.REPEAT_MODE_NONE -> setRepeatMode(RepeatMode.REPEAT_MODE_SHUFFLE)
                RepeatMode.REPEAT_MODE_SHUFFLE -> setRepeatMode(RepeatMode.REPEAT_MODE_ONE)
                RepeatMode.REPEAT_MODE_ONE -> setRepeatMode(RepeatMode.REPEAT_MODE_NONE)
            }
        }
    }

    fun updatePlayBackState(stage: PlaybackStage) {
        _playBackState.value = stage
    }

    //刷新歌曲列表
    fun refreshPlayList(songInfoList: List<SongInfo>) {
        _playList.value = songInfoList.filter { it.songUrl.isNotEmpty() }
        StarrySky.with().updatePlayList(_playList.value as MutableList<SongInfo>)
    }
//    fun refreshPlayList(songInfo: SongInfo) {
//        _playList.value = listOf(songInfo)
//        StarrySky.with().updatePlayList(_playList.value as MutableList<SongInfo>)
//    }

    /**
     * 传入列表和下标并播放
     */
    fun playByListAndIndex(songInfoList: List<SongInfo>?, index: Int) {
        songInfoList?.let { list ->
            _playList.value = list.filter { it.songUrl.isNotEmpty() }
            StarrySky.with().playMusic(_playList.value as MutableList<SongInfo>, index)
        }
    }

    fun playBySong(song: Song) {
        playMusicBySongInfo(song.convertToSongInfo())
    }

    fun playMusicBySongInfo(songInfo: SongInfo) {
        StarrySky.with().playMusicByInfo(songInfo)
    }

}